import {Mat4, toRadian, Vec3} from "../../../src/math";
import {App} from "./App";

export class Camera{

    _projMat:Mat4 = new Mat4();
    _viewMat:Mat4 = new Mat4();
    _worldMat:Mat4 = new Mat4();
    _xAxis:Vec3 = new Vec3(1,0,0);
    _yAxis:Vec3 = new Vec3(0,1,0);
    _zAxis:Vec3 = new Vec3(0,0,1);
    _position:Vec3 = new Vec3();

    _gl:WebGL2RenderingContext;
    public constructor(fovy:number = 60,near:number = 0.1,far:number= 1000) {
        let fovRad = toRadian(fovy);
        let app = App.instance();
        let width = app.width;
        let height = app.height;
        this._gl = app.gl;
        Mat4.perspective(this._projMat,fovRad,width/height,near,far);
    }

    public update(){

        // 计算 viewMatrix
        this._zAxis.normalize();
        Vec3.cross(this._yAxis,this._zAxis,this._xAxis);
        this._yAxis.normalize();

        Vec3.cross(this._xAxis,this._yAxis,this._zAxis);
        this._xAxis.normalize();

        //
        this._worldMat.set(
            this._xAxis.x,this._xAxis.y,this._xAxis.z,0,
            this._yAxis.x,this._yAxis.y,this._yAxis.z,0,
            this._zAxis.x,this._zAxis.y,this._zAxis.z,0,
            this._position.x,this._position.y,this._position.z,1
        );
        Mat4.invert(this._viewMat,this._worldMat);
    }

    get projMat(){
        return this._projMat;
    }

    get viewMat(){
        return this._viewMat;
    }

    get worldMat(){
        return this._worldMat;
    }

    set position(pos:Vec3){
        this._position.set(pos);
    }
}
